package com.trxy.controller.front;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.trxy.mapper.DetailMapper;
import com.trxy.model.Customer;
import com.trxy.model.Detail;
import com.trxy.model.Porder;
import com.trxy.model.Product;
import com.trxy.service.PorderService;
import com.trxy.service.ProductService;
import com.trxy.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    PorderService porderService;
    @Autowired
    ProductService productService;
    @Autowired
    DetailMapper detailMapper;

    //刷新
    @RequestMapping("/product/newPage")
    String newPage(){
        return "redirect:/front/browse/product/list";
    }
    //购物车清单页
    @RequestMapping("/product/detail")
    String productDetail(int porderId, Model model){
        Porder porder = porderService.selectByPrimaryKey(porderId);
        model.addAttribute("Porder", porder);

        //查清单中的所有物品
        List<Detail> detailList = porderService.details(porderId);
        model.addAttribute("DetailList", detailList);
        System.out.println ("detailList是"+detailList);
        if (detailList.isEmpty ()){
            return "redirect:/front/browse/product/list";
        }else {
            return "front/cart/product_detail";
        }
    }

    @RequestMapping("/product/detailBuy")
    String productDetailBuy(int porderId, Model model){
        Porder porder = porderService.selectByPrimaryKey(porderId);
        model.addAttribute("Porder", porder);

        //查清单中的所有物品
        List<Detail> detailList = porderService.details(porderId);
        model.addAttribute("DetailList", detailList);
        System.out.println ("detailList是"+detailList);
        if (detailList.isEmpty ()){
            return "redirect:/front/browse/product/list";
        }else {
            return "front/cart/product_detailbuy";
        }
    }

    @RequestMapping("/product/deleteShop")
    String deleteShop(Integer id, HttpSession session){
        System.out.println(id);
        Object productId = session.getAttribute ("productId");
        System.out.println ("productId是"+session.getAttribute ("productId"));
        detailMapper.deleteShop(id);
        return "redirect:/cart/product/detail?porderId="+productId;
    }

    @RequestMapping("/product/add")
    String productAdd(int id, @RequestParam(required = false, defaultValue = "1") Integer quantity, HttpSession session) {
        int porderId = getPorderId(session);
        int productId = id;
        session.setAttribute ("productId",porderId);

        Product product = productService.selectByPrimarykey(id);

        //形成detail的记录，并加入到detail表
        int num = porderService.addDetail(new Detail(porderId,productId,quantity,product.getPrice()));
        if(num>0){
            return "redirect:detail?porderId=" + porderId;
        }else{
            return "redirect:detail?porderId=" + porderId;
        }
    }

    @RequestMapping("/product/buy")
    String productBuy(int id, @RequestParam(required = false,defaultValue = "1") Integer quantity, HttpSession session){
        int porderId = getPorderId(session);
        int productId = id;

        Product product = productService.selectByPrimarykey(id);

        //形成detail的记录，并加入到detail表
        int num = porderService.addDetail(new Detail(porderId,productId,quantity,product.getPrice()));
        if(num>0) {
            return "redirect:detailBuy?porderId=" + porderId;
        }else {
            return "redirect:detail?porderId=" + porderId;
        }
    }

    @RequestMapping("/product/changeQuantity")
    @ResponseBody
    String changeQuantity(Integer porderId, Integer productId, int target){
        int num = porderService.changeQuantity(porderId, productId, target);
        System.out.println("修改的条数=" + num);
        if(num>0) return "ok";
        else return "fail";
    }

    //提交购物车，状态变成1，等待付款
    @RequestMapping("/product/commit")
    String commit(Integer porderId, HttpSession session){
        //1.计算总金额
        double total = 0;
        List<Detail> details = porderService.details(porderId);
        for(Detail one : details){
            total = total +  one.getQuantity() * one.getPrice();
        }

        //2.状态变成1
        int status = 1;

        //3.生成outTradeNo
        String outTradeNo = OrderUtil.createNo()+ "_" + ((Customer)session.getAttribute("CUSTOMER")).getId();

        int num = porderService.commit(porderId, total, status, outTradeNo);


        //重定向 //去订单信息页
        return "redirect:info?porderId=" + porderId;
    }

    @RequestMapping("/product/info") //显示”去支付”的按钮
    String info(int porderId, Model model){
        Porder porder = porderService.selectByPrimaryKey(porderId);
        model.addAttribute("Porder",porder);
        return  "front/cart/porder_info";
    }

    /**
     *
     */
    @Autowired
    AlipayConfig alipayConfig;

    @RequestMapping("/product/pay")
        //支付时会得到 一个porderid 拿到价格
    void pay(int porderId, HttpServletResponse resp, HttpServletRequest req) throws AlipayApiException, IOException {
        //HttpServletRequest req以及String path用于计算项目名
        String path = req.getContextPath();
        //拿到porder对象
        Porder porder = porderService.selectByPrimaryKey(porderId);

        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //支付成功时，支付路径http://localhost:8080+ 项目名+ (RequestMapping:) cart/product/payInfo
        request.setReturnUrl("http://localhost:8080" + path + "/cart/product/payInfo");
        //request.setNotifyUrl("https://");

        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        //获取OutTradeNo(状态码：年月日时分秒_)
        model.setOutTradeNo(porder.getOutTradeNo());
        //Total转成字符串toString
        model.setTotalAmount(porder.getTotal().toString());
        //Id
        model.setSubject(porder.getId() + "号订单的主题");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        request.setBizModel(model);
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        //产生表单
        String result = response.getBody();
        String head = "<html><head></head><body>";
        String bottom = "</body></html>";
        String html = head + result + bottom;
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println(html);
    }


    @RequestMapping("/product/payInfo")
    String payInfo(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            // 乱码解决
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        // 调用SDK验证签名 //验证这个信息确实是支付宝发过来的
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());

        String queryString = request.getQueryString();
        System.out.println("订单支付成功, 支付宝给添加的参数是=" + queryString + ",验证签名的结果=" + signVerified);

        if (!signVerified) {
            return "error"; //验证失败的情况
        } else {
            // 支付宝交易号
            String trade_no = request.getParameter("trade_no");
            // 商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            // 付款金额
            double total_amount = Double.parseDouble(request.getParameter("total_amount"));

            int num = porderService.changeStatus(out_trade_no, 2);

            Porder porder = porderService.selectByOutTradeNo(out_trade_no);
            request.setAttribute("Porder", porder);
            return "front/cart/porder_payInfo";
        }
    }

    //获取购物车（如果已有就直接用，没有的话就产生一个新的）
    int getPorderId(HttpSession session){
        Integer porder_id= (Integer) session.getAttribute("PORDER_ID");
        if(porder_id==null){
            Customer customer = (Customer)session.getAttribute("CUSTOMER");
            //生成一个新的订单记录
            Porder porder = porderService.create(customer);//获得porder_id
            session.setAttribute("PORDER_ID", porder.getId());
            return porder.getId();//把这个porder_id返回
        }else{
            return porder_id;
        }

    }

}
